package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.itheima.constant.IndexConstant;
import com.itheima.dto.UserLoginDTO;
import com.itheima.entity.Menu;
import com.itheima.entity.SysDict;
import com.itheima.entity.SysUser;
import com.itheima.entity.UserInfo;
import com.itheima.mapper.SysDictMapper;
import com.itheima.mapper.SysUserMapper;
import com.itheima.properties.JwtProperties;
import com.itheima.result.BaseContext;
import com.itheima.service.IndexService;
import com.itheima.utils.IpUtils;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.LoginTokenVO;
import com.itheima.vo.MenuVO;
import com.itheima.vo.ProfileVO;
import com.itheima.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @projectName: kafka
 * @package: com.itheima.service.impl
 * @className: SysUserServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2023/9/20 0:18
 * @version: 1.0
 */
@Service
@RequiredArgsConstructor
public class IndexServiceImpl implements IndexService {
    private final SysUserMapper sysUserMapper;
    private final SysDictMapper sysDictMapper;
    private final IpUtils ipUtils;
    private final JwtProperties jwtProperties;

    @Override
    public LoginTokenVO login(UserLoginDTO userLoginDTO) {
        SysUser user = sysUserMapper.selectUser(userLoginDTO.getLogin_name());
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名不存在!");
        }
        String md5password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        if (!md5password.equals(user.getPassword())){
            throw new RuntimeException("密码错误!");
        }

        // 更新数据
        user.setLoginIp(ipUtils.getClientIp());
        sysUserMapper.updateSysUser(user);

        HashMap<String, Object> map = new HashMap<>();
        map.put(IndexConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), map);

        return LoginTokenVO.builder().token(token).build();
    }

    @Override
    public ProfileVO getUserInfo() {
        ProfileVO profileVO = new ProfileVO();

        UserInfoVO userInfoVO = getUserInfoVO();
        List<MenuVO> menuVOs = getMenuVOList(userInfoVO);
        Map<String,Object> dictsListMap = getDictsListMap();
        List<String> btnList = getBtnList();

        profileVO.setUserInfo(userInfoVO);
        profileVO.setMenuList(menuVOs);
        profileVO.setDictsList(dictsListMap);
        profileVO.setBtnList(btnList);
        return profileVO;
    }

    private UserInfoVO getUserInfoVO() {
        SysUser sysUser = sysUserMapper.selectUserById(BaseContext.getLoginUserId());
        String roleIdJsonArr = sysUser.getRoleId();
        UserInfoVO userInfoVO = new UserInfoVO();
        if (!Objects.isNull(roleIdJsonArr)){
            JSONArray roleIds = JSON.parseArray(roleIdJsonArr);
            List<String> roleIdsJavaList = roleIds.toJavaList(String.class);
            userInfoVO.setRole_id(roleIdsJavaList);
            List<String> roleNameList = sysUserMapper.selectRoleNameByIds(roleIdsJavaList);
            userInfoVO.setRolename(roleNameList);
        }
        userInfoVO.setId(sysUser.getId());
        userInfoVO.setLogin_name(sysUser.getLoginName());
        userInfoVO.setPassword(null);
        userInfoVO.setName(sysUser.getName());
        userInfoVO.setEmail(sysUser.getEmail());
        userInfoVO.setPhone(sysUser.getPhone());
        userInfoVO.setLogin_ip(sysUser.getLoginIp());
        userInfoVO.setLogin_date(sysUser.getLoginDate());
        userInfoVO.setCreate_date(sysUser.getCreateDate());
        userInfoVO.setUpdate_date(sysUser.getUpdateDate());
        userInfoVO.setDel_flag(sysUser.getDelFlag());
        userInfoVO.setStatus(sysUser.getStatus());
        return userInfoVO;
    }

    private List<MenuVO> getMenuVOList(UserInfoVO userInfoVO) {
        List<Menu> menus = sysUserMapper.selectMenusByRoleIds(userInfoVO.getRole_id());
        return menus.stream().map(sysMenu -> {
            MenuVO menuVO = new MenuVO();
            menuVO.setId(sysMenu.getId());
            menuVO.setPid(sysMenu.getPid());
            menuVO.setPath(sysMenu.getPath());
            menuVO.setComponent(sysMenu.getComponent());
            menuVO.setTitle(sysMenu.getTitle());
            menuVO.setIcon(sysMenu.getIcon());
            menuVO.setIs_show(sysMenu.getIsShow());
            menuVO.setIs_cache(sysMenu.getIsCache());
            menuVO.setIs_link(sysMenu.getIsLink());
            menuVO.setRedirect(sysMenu.getRedirect());
            menuVO.setCreateDate(sysMenu.getCreateDate());
            menuVO.setUpdateDate(sysMenu.getUpdateDate());
            menuVO.setDel_flag(sysMenu.getDelFlag());
            menuVO.setType(sysMenu.getType());
            menuVO.setSort(sysMenu.getSort());
            menuVO.setMark(sysMenu.getMark());
            return menuVO;
        }).collect(Collectors.toList());
    }

    private Map<String, Object> getDictsListMap() {
        HashMap<String,Object> result = new HashMap<>(16);
        List<SysDict> sysDictList = sysDictMapper.selectDictList();
        sysDictList.forEach(sysDict -> {
            HashMap<String, Object> item = new HashMap<>(8);
            item.put(sysDict.getValue(), sysDict.getLabel());
            result.put(sysDict.getType(), item);
        });
        return result;
    }

    private List<String> getBtnList() {
        ArrayList<String> btnList = new ArrayList<>();
        btnList.add("*");
        return btnList;
    }
}
